package com.shiwei.is.transmission;

import android.util.Log;

import com.shiwei.is.tools.Helper;

import java.util.Stack;

import okhttp3.WebSocket;

/**
 * File: null.java
 * Creator: dingpwen
 * Company: shiwei
 * Created on: 2021/3/25 13:31
 * Email: dingpwen@gmail.com
 * Details: TODO
 */
class SenderThread extends Thread {
    private volatile boolean isRunning = true;
    private final Stack<ByteArray> dataStack = new Stack<>();
    private final Object lockObj = new Object();
    private WebSocket webSocket;

    public void setWebSocket(WebSocket webSocket) {
        this.webSocket = webSocket;
    }

    //private TestWrite tw;
    //public void setTestWrite(TestWrite tw) { this.tw = tw;}

    public synchronized void send(byte[] videoBuffer, int size){
        ByteArray byteArray = new ByteArray();
        byteArray.data = videoBuffer;
        byteArray.size = size;
        dataStack.push(byteArray);
        notifyAll();
    }

    @Override
    public void run() {
        while(isRunning) {
            synchronized (this) {
                try {
                    if (dataStack.isEmpty()) {
                        Log.d("ISApp:SenderThread", "wait for data");
                        wait();
                    }
                    ByteArray byteArray = dataStack.pop();
                    //Log.d("ISApp:SenderThread", "size = " + byteArray.size);
                    if(webSocket != null) {
                        webSocket.send(Helper.addToSizeByteArray(byteArray.data, byteArray.size));
                        //tw.writeFile(byteArray.data, byteArray.size);
                    }
                    synchronized(lockObj){
                        lockObj.wait(10);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public void exit(){
        isRunning = false;
        if(webSocket != null) {
            webSocket.close(1000, "Normal");//RFC 6455
            webSocket = null;
            //tw.exit();
        }
        interrupt();
    }

    static class ByteArray{
        byte[] data;
        int size;
    }

    /*@Override
    public void run() {
        int size = 20480;
        synchronized (this) {
            try {
                while(webSocket == null) {
                    sleep(100);
                }
                byte[] data = new byte[size];
                int len = 0;
                while((len = tw.readFile(data, size)) > 0){
                    webSocket.send(Helper.addToSizeByteArray(data, len));
                    synchronized(lockObj){
                        lockObj.wait(10);
                    }
                }
                exit();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }*/
}
